package com.lt.reggie.controller;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.lt.reggie.common.R;
import com.lt.reggie.entity.User;
import com.lt.reggie.service.UserService;
import com.lt.reggie.utils.SMSUtils;
import com.lt.reggie.utils.ValidateCodeUtils;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;
import java.util.Map;
import java.util.concurrent.TimeUnit;

/**
 * 移动端用户管理
 */
@RestController
@RequestMapping("/user")
@Slf4j
public class UserController {

    @Autowired
    private UserService userService;

    @Autowired
    private RedisTemplate redisTemplate;
    /**
     * 移动端获取验证码
     *
     * @param user
     * @param session
     * @return
     */
    @PostMapping("/sendMsg")
    public R<String> sendMsg(@RequestBody User user, HttpSession session) {
        //获取手机号
        String phone = user.getPhone();
        //判断手机号是否为空
        if (StringUtils.isNotEmpty(phone)) {
            //生成随机4位验证码
            String code = ValidateCodeUtils.generateValidateCode(4).toString();
            //将验证码存入session
//            session.setAttribute(phone,code);
            //将生成的验证码存入redis中,并设置5分钟最大存活时间
            redisTemplate.opsForValue().set(phone,code,5, TimeUnit.MINUTES);
            log.info("code = {}", code);
            //调用阿里云提供的短信服务API完成发送短信
//            SMSUtils.sendMessage(phone,code);
//            SMSUtils.sendMSM(phone, code);
            return R.success("短信发送成功");
        }
        return R.error("短信发送失败");
    }

    /**
     * 移动端登录
     *
     * @return
     */
    @PostMapping("/login")
    public R<User> login(@RequestBody Map map, HttpSession session) {
        log.info("map = {}", map);
        //获取手机号
        String phone = map.get("phone").toString();
        //获取验证码
        String code = map.get("code").toString();
        //从session中获取保存的验证码
//        String codeInSession = session.getAttribute(phone).toString();
        //从redis中获取验证码
        String codeInRedis = (String) redisTemplate.opsForValue().get(phone);
        //进行验证码较对
        if (codeInRedis.equals(code)) {
            //比对成功，则登录成功
            //判断当前手机号是否位新用户，如果是则自动完成注册
            LambdaQueryWrapper<User> queryWrapper = new LambdaQueryWrapper<>();
            queryWrapper.eq(User::getPhone, phone);
            User user = userService.getOne(queryWrapper);

            if (user == null) {
                user = new User();
                //当前手机号时新用户，进行自动注册
                user.setPhone(phone);
                user.setStatus(1);
                userService.save(user);
            }
            //将用户id传入session做登录校验
            Long userId = user.getId();
            session.setAttribute("user",userId);
            log.info(session.getAttribute("user").toString());
            //登录成功删除redis中缓存的验证码
            redisTemplate.delete(phone);
            return R.success(user);
        }
        return R.error("登录失败");
    }

    /**
     * 移动端用户登出
     * @return
     */
    @PostMapping("/loginout")
    public R<String> loginOut(HttpServletRequest request){
        request.getSession().removeAttribute("user");
        return R.success("登出成功");
    }
}
